﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using WxPayAPI;

namespace WxPayJSAPI.Controllers
{
    public class JuHePayController : Controller
    {
        //登陆地址：http://www.zhongjin-zf.com:8080/merch/userLogin.html
        //机构号：2000440305
        //商户号：200110254110003
        //登陆名：13388435935
        //密码：435935
        //密钥：67B2B978945294ADB62D939D55A2A836
        string merchno = "200110254110003";

        // GET: JuHePay
        public ActionResult Index()
        {
            return View();
        }




        public string pay()
        {
            var traceno = new Random().Next(11111111, 999999999).ToString();

            var ss = new Dictionary<string, object>();
            ss.Add("amount", 0.01);
            ss.Add("callbackUrl", "http://47.90.72.183:7022/JuHePay/succ");
            ss.Add("goodsName", "Online recharge"+traceno);
            ss.Add("interfacetype", "4");
            ss.Add("merchno", "200110254110003");
            ss.Add("notifyUrl", "http://47.90.72.183:7022/JuHePay/notify");
            ss.Add("payType", 2);
            ss.Add("settleType", 1);
            ss.Add("traceno", traceno);
            ss.Add("version", 1.5);
            //ss.Add("key",  "67B2B978945294ADB62D939D55A2A836");

            var surl = createLinkString(ss);

            var stringsignTemp = surl + "&key=67B2B978945294ADB62D939D55A2A836";
            var sign = String_ext.md5(stringsignTemp).ToUpper();

            ss.Add("sign", sign);


            var s = postraw("http://api.zhongjin-zf.com:8088/b2c/payment/order", JsonConvert.SerializeObject(ss));

            /// 接口完整返回值
            var p = JsonConvert.DeserializeObject<Dictionary<string, object>>(s);
            if (Convert.ToString(p["respCode"]) == "1")
            {
                s = Convert.ToString(p["barCode"]);
            }
            /// 
            return s;
        }

        public ActionResult notify(string respCode,string outTradeNo,string payStatus)
        {
            Log.Error(this.GetType().ToString(), "notify 聚合支付 ======"+ respCode + "=  订单号："+ outTradeNo + "  支付状态：付款状态(0-待支付 1-未支付 2-已支付 3-支付失败)" + payStatus);

            return View(respCode);
        }

        public ActionResult succ(string respCode, string outTradeNo, string payStatus)
        {
            Log.Error(this.GetType().ToString(), "succ 聚合支付 =====" + respCode + "=  订单号：" + outTradeNo + "  支付状态：付款状态(0-待支付 1-未支付 2-已支付 3-支付失败)" + payStatus);
            return View(respCode);
        }



        public string postraw(string url, string jsonString)
        {

            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            //            request.AddParameter("undefined", "{\"ddd\":\"eee\"}", ParameterType.RequestBody);

            request.AddParameter("application/json; charset=utf-8", jsonString, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            var responseContent = response.Content;
            return responseContent;
        }



        /**
         * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
         * @param params 需要排序并参与字符拼接的参数组
         * @return 拼接后字符串
         */
        public string createLinkString(Dictionary<string, object> param)
        {
            var keys = param.Select(x => x.Key).ToList();
            keys.Sort();


            string prestr = "";
            for (int i = 0; i < keys.Count; i++)
            {
                string key = keys[i];
                object value = param[key];
                if (value != null && value != "")
                {
                    if (i == keys.Count - 1)
                    {//拼接时，不包括最后一个&字符
                        prestr = prestr + key + "=" + value;
                    }
                    else
                    {
                        prestr = prestr + key + "=" + value + "&";
                    }
                }
            }
            return prestr;
        }
    }
}